package moodish.comm;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

import moodish.dummy.ServerCommDummy;
import moodish.message.MessageFromClient;

/**
 * Thread started by a new Client when connects successful to the Moodish server. 
 * The server uses this Thread to receive messages from the client.
 * This will execute until the server receive a Disconnected message from this specific client.
 *  
 */
public class ListenMessagesFromClient implements Runnable {
	private ObjectInputStream fromClient;
	private ObjectOutputStream toClient;
	private Socket clientSocket;
	private ServerCommDummy scd;
	private MessageFromClient message;
	
	public ListenMessagesFromClient(Socket clientSocket, ServerCommDummy scd)
	{
		try {
			this.clientSocket = clientSocket;
			this.scd=scd;
			fromClient = new ObjectInputStream(clientSocket.getInputStream());
			this.toClient = new ObjectOutputStream(clientSocket.getOutputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/** 
	 * This method returns the socket to communicate with the client.
	 * 
	 * @return The Socket to communicate with this specific client
	 */
	public Socket getSocket()
	{
		return clientSocket;
	}


	@Override
	public void run() {
			while(true)
			{
				try {
					message = (MessageFromClient)fromClient.readObject();
				} catch (ClassNotFoundException | IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
					scd.addMessage(message);
					if(message.getType().equals(ServerSideMessage.Type.CLIENT_CONNECTED))
					{
						scd.addConnectedClient(message.getClientNickname(),this);
					}
					else if(message.getType().equals(ServerSideMessage.Type.CLIENT_DISCONNECTED))
					{
						break;
					}
			}
			
			scd.disconnectClient(message.getClientNickname());
		
			
			
			
		// TODO Auto-generated method stub
		
	}

	/** 
	 * This Method will return the ServerCommDummy class.
	 * @return The ServerCommDummy class.
	 */
	public ServerCommDummy getScd() {
		return scd;
	}


	/** 
	 * This Method will return the ObjectOutputStream to the server sent messages to the client
	 * @return The ObjectOutputStream from this specific client.
	 */
	public ObjectOutputStream getToClient() {
		return toClient;
	}

}
